﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Configuration;
using HelloWorldBll;
using HelloWorldBll.Helper;
using MessageBox = System.Windows.Forms.MessageBox;


namespace Sinobase_CollectForPHP
{
    public partial class Form1 : Form
    {
        #region  声明字段

        /// <summary>
        /// 用于窗体显示的日志文件，
        /// </summary>
        string temp_log = "";
        /// <summary>
        /// 开始时间
        /// </summary>
        DateTime startdate = DateTime.Today.AddDays(-1);
        /// <summary>
        /// 结束时间
        /// </summary>
        DateTime enddate = DateTime.Today.AddDays(-1);
        /// <summary>
        /// 设置更新时间
        /// </summary>
        DateTime lastdate;
        /// <summary>
        /// 用于显示的图片的索引
        /// </summary>
        int imageindex = 0;
        const string SERVICETYPE = "TM";
        const string APPLICATION = "PHP_CALLCENTER";
        /// <summary>
        /// 声明数据库连接字符串
        /// </summary>
        string strConnect = string.Empty;
        /// <summary>
        /// 标记是用户还是自动关闭程序
        /// </summary>
        bool userclose = true;
        /// <summary>
        ///标记执行命令ID
        /// </summary>
        int taskid = 0;
        /// <summary>
        /// 标记命令执行的项目ID
        /// </summary>
        string Identifiers = string.Empty;

        #endregion

        #region  构造

        public Form1()
        {
            InitializeComponent();
        }

        #endregion

        #region 事件

        private void F_Main_Load(object sender, EventArgs e)
        {
            LoadApp();
            ini();
        }

        private void bt_query_Click(object sender, EventArgs e)
        {
            RunWorker();
        }
        #endregion

        #region 公共方法

        /// <summary>
        /// 初始化
        /// </summary>
        private void ini()
        {
            DateTimePicker dtpbeg = new DateTimePicker();
            dtpbeg.Format = DateTimePickerFormat.Custom;//自动设置
            dtpbeg.CustomFormat = "yyyy-MM-dd";//自定义格式 
            dtpbeg.Width = 100;
            Controls.Add(dtpbeg);
            //添加的位置
            this.toolStrip1.Items.Insert(3, new ToolStripControlHost(dtpbeg));
            DateTimePicker dtpend = new DateTimePicker();
            dtpend.Format = DateTimePickerFormat.Custom;//自动设置
            dtpend.CustomFormat = "yyyy-MM-dd";//自定义格式 
            dtpend.Width = 100;
            Controls.Add(dtpend);
            //添加的位置
            this.toolStrip1.Items.Insert(5, new ToolStripControlHost(dtpend));

            t_result.Text = "";
            t_form.Start();
            t_getdata.Start();
            icon_work.Image = imageList.Images[0];
        }
        /// <summary>
        /// 启用收集事件(checkServerUpload：是否检验收集过数据)
        /// </summary>
        /// <param name="checkServerUpload"></param>
        private void RunWorker()
        {
            startdate = Convert.ToDateTime(toolStrip1.Items[3].Text);
            enddate = Convert.ToDateTime(toolStrip1.Items[5].Text);
            bg_getdata.RunWorkerAsync();
        }
        /// <summary>
        /// 将数据写入文件
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="filename"></param>
        public void WriteData(DataTable dt, string filename)
        {
            StringBuilder data = new StringBuilder();

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                data.Append(dt.Columns[i].ColumnName.Replace("\t", ""));
                if (i != dt.Columns.Count - 1)
                {
                    data.Append("\t");
                }
                else
                {
                    data.Append("\r\n");
                }
            }
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                for (int k = 0; k < dt.Columns.Count; k++)
                {
                    data.Append(dt.Rows[j][k].ToString().Replace("\t", "").Replace("\n", "").Replace("\r", ""));
                    if (k != dt.Columns.Count - 1)
                    {
                        data.Append("\t");
                    }
                    else
                    {
                        data.Append("\r\n");
                    }
                }
            }
            if (File.Exists(filename))
            {
                File.Delete(filename);
            }

            StreamWriter sw = new StreamWriter(filename, true);
            sw.WriteLine(data);
            sw.Close();
        }

        delegate void changeEnabled(bool state);
        /// <summary>
        /// 设置 开始/结束 收集时各控件的状态
        /// </summary>
        public void SetThreeState(bool state)
        {
            if (state)
            {
                t_getdata.Start();
                //工作图标状态恢复
                imageindex = 0;
            }
            else
            {
                t_getdata.Stop();
                //工作图标状态
                imageindex = 1;
            }
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new changeEnabled(SetThreeState), state);
            }
            else
            {
                btnSave.Enabled = state;
                bt_query.Enabled = state;
                btnRevert.Enabled = state;
                tb_UpFile.Enabled = state;
            }
        }
        #endregion

        #region 提示 错误信息
        StringBuilder strbuilder = new StringBuilder();
        /// <summary>
        ///  显示输出
        /// </summary>
        /// <param name="str"></param>
        void addtext(string str)
        {
            temp_log += str + "\r\n";
            // CollectorNetLib.Systems.Log.logByDay(str);
        }
        void addtext(string str, string strtitle)
        {
            temp_log += str + "\r\n";
            // CollectorNetLib.Systems.Log.logByDay(str);
            strbuilder.Append(str + "\r\n");
        }
        void addtext()
        {
            try
            {
                //new CollectorNetLib.Collection.CollectionLog().SendEmal("TM-PHP(" + txtcallcenter.Text + "呼叫中心）", strbuilder.ToString(), txtEmail.Text, txtWSUID.Text, txtWSPWD.Text);
            }
            catch (Exception ex)
            {
                addtext("发送email异常" + ex.Message);
            }
            strbuilder = new StringBuilder();

        }
        #endregion

        #region 方法
        /// <summary>
        /// 获取所有项目列表
        /// </summary>
        /// <returns>项目列表</returns>
        private DataTable getProjectByAll()
        {
            DataTable result = new System.Data.DataTable();
            try
            {
                //result = new CollectorNetLib.Data.MysqlHelper(strConnect).getTable("SELECT * FROM oc_project").Tables[0];

            }
            catch (Exception ex)
            {
                addtext(string.Format("查询项目表数据发生异常:" + ex.Message), "TM-PHP(" + txtcallcenter.Text + "呼叫中心）获取所有项目列表异常");
            }
            return result;
        }
        /// <summary>
        /// 根据项目ID获取项目
        /// </summary>
        /// <param name="projectid"></param>
        /// <returns></returns>
        private System.Data.DataTable getProjectByProjectid(string projectid)
        {
            DataTable result = new System.Data.DataTable();
            try
            {
                //result = new CollectorNetLib.Data.MysqlHelper(strConnect).getTable(string.Format("SELECT * FROM oc_project as a where a.pro_id='{0}'", projectid)).Tables[0];
            }
            catch (Exception ex)
            {
                addtext("\t获取项目表错：" + ex.Message, "TM-PHP(" + txtcallcenter.Text + "呼叫中心）获取项目异常");
            }
            return result;
        }
        /// <summary>
        /// 根据项目编号获取问卷题目表
        /// </summary>
        /// <param name="projectid">项目编号</param>
        /// <returns>问卷题目表</returns>
        private DataTable getProjectQuestionByProjectID(string projectid)
        {
            DataTable result = new System.Data.DataTable();
            try
            {
                string sql = string.Format(@"SELECT 	cpq_id,
	        cpq_title
	        FROM 
	        oc_cpq 
	        WHERE cpq_pro_id={0} order by cpq_order", projectid);
                //result = new CollectorNetLib.Data.MysqlHelper(strConnect).getTable(sql).Tables[0];
            }
            catch (Exception ex)
            {
                addtext("\t根据项目编号获取问卷题目表出错：" + ex.Message, "TM-PHP(" + txtcallcenter.Text + "呼叫中心" + projectid + "项目）获取问卷题目表异常");

            }
            return result;
        }
        /// <summary>
        /// 根据项目编号获取项目字段列表
        /// </summary>
        /// <param name="projectid">项目编号</param>
        /// <returns>字段列表</returns>
        private DataTable getProjectFieldsByProjectID(string projectid)
        {
            DataTable result = new System.Data.DataTable();
            try
            {
                string sql = string.Format(@"
            SELECT 		field_sys_name, 
	            field_show_name
	            FROM 
	            oc_oc_pro_field_{0} ", projectid);
                // result = new CollectorNetLib.Data.MysqlHelper(strConnect).getTable(sql).Tables[0];
            }
            catch (Exception ex)
            {
                addtext("\t根据项目编号获取项目字段列表数据出错：" + ex.Message, "TM-PHP(" + txtcallcenter.Text + "呼叫中心" + projectid + "项目）获取项目字段列表异常");
            }
            return result;
        }
        /// <summary>
        /// 根据字段列表和项目编号获取查询语句中的字段列表字符串
        /// </summary>
        /// <param name="dt_projectfield">字段列表</param>
        /// <param name="projectid">项目编号</param>
        /// <returns>字段列表字符串</returns>
        private string getProjectSelectStringByProjectID(DataTable dt_projectfield, string projectid, int secondstart, int secondend)
        {
            string result = "";
            string selectfields = string.Format("info_id  as `流水号`,'{0}' as `抽取时间`,", DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd"));
            if (dt_projectfield.Rows.Count > 0)
            {

                for (int i = 0; i < dt_projectfield.Rows.Count; i++)
                {
                    selectfields += string.Format("oc_pro_data_tname_{2}.{0} as `{1}`", dt_projectfield.Rows[i]["field_sys_name"].ToString(), dt_projectfield.Rows[i]["field_show_name"].ToString(), projectid);
                    if (i != dt_projectfield.Rows.Count - 1)
                    {
                        selectfields += ",";
                    }
                }
                if (selectfields == string.Format("info_id as `流水号`,'{0}' as `抽取时间`,", DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd")))
                {
                    selectfields = "*";
                }
                else
                {
                    selectfields = selectfields.Replace(string.Format("oc_pro_data_tname_{0}.info_ocstate", projectid), string.Format("oc_pro_call_state_{0}.c_name", projectid));
                }
                result = selectfields;

                string sql_question = string.Format(@"SELECT 	cpq_id,
	cpq_title
	FROM 
	oc_cpq 
	WHERE cpq_pro_id={0} order by cpq_order", projectid);
                DataTable dt_projectquestion = getProjectQuestionByProjectID(projectid);
                string questionfields = "";
                for (int j = 0; j < dt_projectquestion.Rows.Count; j++)
                {
                    questionfields += string.Format(@"(SELECT MAX(qa_result)	 
	FROM 
	oc_pro_qa_tname_{2}
	WHERE qa_cpq_id={1} AND qa_info_id=oc_pro_data_tname_{2}.info_id) as `{0}`", dt_projectquestion.Rows[j]["cpq_title"].ToString(), dt_projectquestion.Rows[j]["cpq_id"].ToString(), projectid);
                    if (j != dt_projectquestion.Rows.Count - 1)
                    {
                        questionfields += ",";
                    }
                }

                if (questionfields.Length > 0)
                {
                    result = selectfields + "," + questionfields;
                }
                string companycolumnstatus = @"
info_isright0 AS `公司名称核实状态`, 
info_isright1 AS `行业核实状态`, 
info_isright2 AS `企业性质核实状态`, 
info_isright3 AS `省市县核实状态`, 
info_isright4 AS `员工人数核实状态`, 
info_isright5 AS `电脑台数核实状态`, 
info_isright6 AS `年营业额核实状态`, 
info_isright7 AS `注册金额核实状态`, 
info_isright8 AS `联系人姓名核实状态`, 
info_isright9 AS `性别核实状态`, 
info_isright10 AS `部门核实状态`, 
info_isright11 AS `职务核实状态`, 
info_ptel_status AS `个人电话状态`, 
info_isright12 AS `个人电话核实状态`, 
info_isright13 AS `地址核实状态`, 
info_isright14 AS `邮编核实状态`, 
info_ctstatus AS `公司电话状态`, 
info_isright15 AS `公司电话核实状态`, 
info_isright16 AS `传真核实状态`, 
info_mphone_status AS `联系人手机状态`, 
info_isright17 AS `手机核实状态`, 
info_isright18 AS `个人email核实状态`, 
info_isright22 AS `自定义部门核实状态`, 
info_isright23 AS `自定义职务核实状态`, 
info_isright19 AS `服务器台数核实状态`, 
info_isright20 AS `自定义行业核实状态`, 
info_isright21 AS `自定义性质核实状态`";
                string personcolumnstatus = @"
info_isright3 AS `省市县核实状态`, 
info_isright8 AS `联系人姓名核实状态`, 
info_isright9 AS `性别核实状态`, 
info_ptel_status AS `个人电话状态`, 
info_isright12 AS `个人电话核实状态`, 
info_isright13 AS `地址核实状态`, 
info_isright14 AS `邮编核实状态`, 
info_mphone_status AS `联系人手机状态`, 
info_isright17 AS `手机核实状态`, 
info_isright18 AS `个人email核实状态`";
                if (result.ToLower().IndexOf("as `公司名称`") > -1)
                {
                    result += ", " + companycolumnstatus;
                }
                else
                {
                    result += ", " + personcolumnstatus;
                }

            }
            result = string.Format(@"SELECT {0} FROM oc_pro_data_tname_{1},oc_pro_call_state_{1}
                WHERE oc_pro_call_state_{1}.id=oc_pro_data_tname_{1}.info_ocstate and oc_pro_data_tname_{1}.info_edittime>={2} and oc_pro_data_tname_{1}.info_edittime<{3} and oc_pro_call_state_{1}.is_were='1'",
                result, projectid, secondstart, secondend);
            return result;
        }
        /// <summary>
        /// 根据字段列表和项目编号获取查询语句中的字段列表字符串(部分数据)
        /// </summary>
        /// <param name="projectno"></param>
        /// <param name="projectname"></param>
        /// <param name="projectid"></param>
        /// <param name="startdate"></param>
        /// <param name="secondstart"></param>
        /// <param name="secondend"></param>
        /// <returns></returns>
        private string getProjectSummarySelectStringByProjectID(string projectno, string projectname, string projectid, DateTime startdate, int secondstart, int secondend)
        {
            string result = "";
            string sql = @"SELECT  '{7}' AS `应用程序`,
                        '{0}' AS `呼叫中心`,
                        '{1}' AS `项目编号`,
                        '{3}' AS `呼叫中心项目编号`,
                        '{2}' AS `呼叫中心项目名称`,
                        oc_pro_data_tname_{3}.info_id  AS `流水号`,
                        oc_pro_data_tname_{3}.info_Sino_ID AS `公司编号`,
                        oc_pro_data_tname_{3}.info_Per_ID AS `联系人编号`,
                        oc_pro_call_state_{3}.c_name AS `外呼状态`,
                        oc_pro_call_state_{3}.is_were AS '结案否',
                        oc_pro_data_tname_{3}.info_fyname AS `访员名称`,
                        oc_pro_data_tname_{3}.info_edittime AS `更新时间`
                        FROM oc_pro_data_tname_{3},oc_pro_call_state_{3}
                        WHERE  oc_pro_call_state_{3}.id=oc_pro_data_tname_{3}.info_ocstate 
                        and oc_pro_data_tname_{3}.info_edittime>={5} and oc_pro_data_tname_{3}.info_edittime<{6} ";
            result = string.Format(sql, txtcallcenter.Text,
                projectno, projectname, projectid, startdate.ToString("yyyy-MM-dd"), secondstart, secondend,
                APPLICATION);
            return result;
        }

        /// <summary>
        /// 根据项目编号获取项目最大编辑时间
        /// </summary>
        /// <param name="projectid"></param>
        /// <returns></returns>
        private int getProjectMaxEditTimeByProjectID(string projectid)
        {
            int result = 0;
            try
            {
                string sql = string.Format(@"SELECT MAX(info_edittime)
	FROM oc_pro_data_tname_{0}", projectid);
                // string str = new CollectorNetLib.Data.MysqlHelper(strConnect).getValue(sql).ToString();

                //if (string.IsNullOrEmpty(str))
                //{
                //  //  throw new CollectorNetLib.Systems.MyException("\t没有在表oc_pro_data_tname_" + projectid + "中找到最大编辑时间");
                //}
                //  result = Convert.ToInt32(str);
            }
   
            catch (Exception ex)
            {
                if (ex.Message.IndexOf("对象名 'oc_pro_data_tname_" + projectid + "' 无效") >= 0)
                {
                    //throw new CollectorNetLib.Systems.MyException("\t表oc_pro_data_tname_" + projectid + "不存在");
                }
                addtext("\t根据项目编号获取项目最大编辑时间出错：" + ex.Message, "TM-PHP(" + txtcallcenter.Text + "呼叫中心" + projectid + "项目）获取项目最大编辑时间异常");
                throw ex;
            }
            return result;
        }

        /// <summary>
        /// 将开始时间转换成INT型
        /// </summary>
        /// <param name="start">开始时间</param>
        /// <returns>int值</returns>
        private int getSecondStart(DateTime start)
        {
            int result = 0;
            DateTime startdate = new DateTime(1970, 1, 1, 8, 0, 0);
            TimeSpan seconds = start - startdate;
            result = Convert.ToInt32(seconds.TotalSeconds);
            return result;
        }

        /// <summary>
        /// 将结束时间转换成INT型
        /// </summary>
        /// <param name="end">结束时间</param>
        /// <returns>int值</returns>
        private int getSecondEnd(DateTime end)
        {
            int result = 0;
            DateTime startdate = new DateTime(1970, 1, 1, 8, 0, 0);
            TimeSpan seconds = end.AddDays(1) - startdate;
            result = Convert.ToInt32(seconds.TotalSeconds);
            return result;
        }

        private DateTime GetDateByIntdate(Int64 stardate)
        {
            Int64 begtime = Convert.ToInt64(stardate) * 10000000;//100毫微秒为单位,textBox1.text需要转化的int日期
            DateTime dt_1970 = new DateTime(1970, 1, 1, 8, 0, 0);
            long tricks_1970 = dt_1970.Ticks;//1970年1月1日刻度
            long time_tricks = tricks_1970 + begtime;//日志日期刻度
            DateTime dt = new DateTime(time_tricks);//转化为DateTime
            return dt;
        }
        #endregion

        #region 数据抽取主方法

        /// <summary>
        /// 数据抽取
        /// </summary>
        /// <param name="ifcheck"></param>
        private void ExtractData()
        {
            DataTable dt_project;
            if (!string.IsNullOrEmpty(Identifiers))
            {
                dt_project = getProjectByProjectid(Identifiers);
                Identifiers = "";
            }
            else
            {
                dt_project = getProjectByAll();

            }
            if (dt_project.Rows.Count > 0)
            {
                addtext(string.Format("当前系统中包含项目总数：{0},下面统计{1}至{2}这段时间内结案的项目数据。", dt_project.Rows.Count, startdate.ToString("yyyy-MM-dd"), enddate.ToString("yyyy-MM-dd")));
                ForeachProject(dt_project);
            }
            lastdate = DateTime.Today;
            addtext("数据抽取结束\r\n");
        }
        /// <summary>
        /// 循环抽取数据
        /// </summary>
        /// <param name="ifcheck"></param>
        /// <param name="dt_project"></param>
        private void ForeachProject(DataTable dt_project)
        {
            List<string> prolist = new List<string>();
            try
            {
                //prolist = new CollectorNetLib.Collection.CollectionLog().GetValidProjectNOList(txtWSUID.Text, txtWSPWD.Text);

            }
            catch (Exception ex)
            {
                addtext(string.Format("获取项目编号集合异常：" + ex.Message), "TM-PHP(" + txtcallcenter.Text + "呼叫中心）获取项目编号集合异常");
            }
            //遍历每个项目
            foreach (DataRow myrow in dt_project.Rows)
            {

                //判断此项目前一天是否有更新
                int secondstart = getSecondStart(startdate);
                int secondend = getSecondEnd(enddate);
                int currentmaxdate = 0;
                try
                {
                    currentmaxdate = getProjectMaxEditTimeByProjectID(myrow["pro_id"].ToString());
                }
                catch (Exception ee)
                {
                    addtext(string.Format("项目：{1}（{0}）\t{2}，本次跳过!", myrow["pro_id"].ToString(), myrow["pro_name"].ToString(), ee.Message));
                    continue;
                }
                catch
                {
                    addtext(string.Format("项目：{1}（{0}）\t无法找到项目数据，本次跳过！", myrow["pro_id"].ToString(), myrow["pro_name"].ToString()));
                    continue;
                }
                if (currentmaxdate > secondstart)
                {

                    //是否存在此项目
                    try
                    {
                        if (prolist == null || prolist.Count == 0 || !prolist.Contains(myrow["pro_num"].ToString()))
                        {
                            addtext(string.Format("内部系统项目编号验证失败：{1}（{0}）\t，本次跳过！", myrow["pro_id"].ToString(), myrow["pro_name"].ToString()));
                            continue;
                        }
                    }
                    catch (Exception ex)
                    {
                        addtext(string.Format("验证内部系统项目编号{1}（{0}） 访问异常：" + ex.Message, myrow["pro_id"].ToString(), myrow["pro_name"].ToString()), "TM-PHP(" + txtcallcenter.Text + "呼叫中心" + myrow["pro_id"].ToString() + "项目）数据收集异常提示");
                        continue;
                    }
                    //获取项目字段列表
                    DataTable dt_projectfield = getProjectFieldsByProjectID(myrow["pro_id"].ToString());
                    string sql = getProjectSelectStringByProjectID(dt_projectfield, myrow["pro_id"].ToString(), secondstart, secondend);
                    string sql_summary = getProjectSummarySelectStringByProjectID(myrow["pro_num"].ToString(), myrow["pro_name"].ToString(), myrow["pro_id"].ToString(), startdate, secondstart, secondend);

                    string file_back, file_summary, targeturl;
                    file_back = string.Format("{0}-{1}-{2}.txt", myrow["pro_id"], myrow["pro_num"], startdate.ToString("yyyyMMdd"));
                    file_summary = string.Format("{0}-{1}-{2}-summary.txt", myrow["pro_id"], myrow["pro_num"], startdate.ToString("yyyyMMdd"));
                    targeturl = string.Format("{3}/{0}/{2}/{1}/", txtcallcenter.Text, myrow["pro_id"].ToString(), APPLICATION, SERVICETYPE);
                    #region 抽取操作
                    try
                    {

                        // DataTable dt_date = new  MysqlHelper(strConnect).getTable(sql).Tables[0];
                        //if (dt_date.Rows.Count == 0)
                        //{
                        //    addtext(string.Format("项目：{1}（{0}）\t没有产生新的数据，本次跳过！", myrow["pro_id"].ToString(), myrow["pro_name"].ToString()));
                        //    continue;
                        //}
                        //开始将项目详细数据写入文本文件
                        // WriteData(dt_date, txtworkdir.Text + file_back);                       
                        //开始从数据库获取项目状态数据
                        // DataTable dt_summarydate = new CollectorNetLib.Data.MysqlHelper(strConnect).getTable(sql_summary).Tables[0];
                        //if (dt_summarydate.Rows.Count == 0)
                        //{
                        //    addtext(string.Format("项目：{1}（{0}）\t没有产生新的数据，本次跳过！", myrow["pro_id"].ToString(),myrow["pro_name"].ToString()));
                        //    continue;
                        //}
                        #region 统计项目包含条数

                        //DataSet ds = new DataSet();
                        //DataTable datedt = new DataTable();
                        //datedt.Columns.Add(new DataColumn("WorkDate", System.Type.GetType("System.DateTime")));
                        //datedt.Columns.Add(new DataColumn("Counts", System.Type.GetType("System.Int32")));
                        //foreach (DataRow row in dt_summarydate.Rows)
                        //{
                        //    DateTime begtime = GetDateByIntdate(Convert.ToInt64(row["更新时间"])).Date;
                        //    Int64 keydate = getSecondStart(begtime);
                        //    Int64 keyenddate = getSecondStart(begtime.AddDays(1));
                        //    if (datedt.Select(string.Format("WorkDate='{0}'", begtime)).Length == 0)
                        //    {
                        //        int keycount = dt_summarydate.Select(string.Format("更新时间 >={0} and 更新时间<{1}", keydate, keyenddate)).Length;
                        //        DataRow dr = datedt.NewRow();
                        //        dr[0] = begtime;
                        //        dr[1] = keycount;
                        //        datedt.Rows.Add(dr);
                        //    }
                        //}
                        //ds.Tables.Add(datedt);
                        // new CollectorNetLib.Collection.CollectionLog().Add(ds, SERVICETYPE, APPLICATION,
                        //          txtcallcenter.Text, myrow["pro_id"].ToString(), "", txtWSUID.Text, txtWSPWD.Text);

                        #endregion
                        //开始将项目状态数据写入文本文件
                        //WriteData(dt_summarydate, txtworkdir.Text + file_summary);
                        //addtext(string.Format("项目:{3}\t处理完成。生成项目详细数据：{0},{1}\t至{2}", file_back, file_summary, txtworkdir.Text, myrow["pro_name"]));


                    }
                    catch (Exception ex)
                    {
                        addtext("\t生成项目详细数据出错：" + ex.Message, "TM-PHP(" + txtcallcenter.Text + "呼叫中心" + myrow["pro_id"].ToString() + "项目）数据收集异常提示");
                    }
                    #endregion
                }
                else
                {
                    addtext(string.Format("项目:{0}在{1}至{2}这段时间内没有更新，跳过。", myrow["pro_name"], startdate.ToString("yyyy-MM-dd"), enddate.ToString("yyyy-MM-dd")));
                }
            }
        }

        /// <summary>
        /// 获取项目条数
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="projectname"></param>
        /// <param name="secondstart"></param>
        /// <param name="secondend"></param>
        /// <returns></returns>
        private int GetProjectItemCount(string projectid, string projectname, int secondstart, int secondend)
        {
            int icount = 0;
            string sql = @"SELECT count(*) FROM oc_pro_data_tname_{0}
                        WHERE  oc_pro_data_tname_{0}.info_edittime>={1} and oc_pro_data_tname_{0}.info_edittime<{2} ";
            string resultsql = string.Format(sql, projectid, secondstart, secondend);
            //object itemcount = new CollectorNetLib.Data.MysqlHelper(strConnect).getValue(resultsql);
            //if (itemcount != null && itemcount != "")
            //{
            //    icount = Convert.ToInt32(itemcount);
            //}
            return icount;
        }

        #endregion

        #region 窗体 timer事件
        /// <summary>
        /// 数据收集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void t_getdata_Tick(object sender, EventArgs e)
        {

            if (DateTime.Now.Hour.ToString() == txtworkhour.Text && DateTime.Now.Minute.ToString() == txtworkmin.Text)
            {
                startdate = DateTime.Today.AddDays(-1);
                enddate = DateTime.Today.AddDays(-1); ;
                if (lastdate != DateTime.Today)
                {
                    bg_getdata.RunWorkerAsync();
                }
            }
        }
        /// <summary>
        /// 负责窗体展示的timer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void t_form_Tick(object sender, EventArgs e)
        {
            showlog();
            checkstatus();
        }
        /// <summary>
        /// 在窗体文本中显示进程
        /// </summary>
        private void showlog()
        {
            if (t_result.Lines.Count() > 100)
                t_result.Text = "";
            if (temp_log.Length > 0)
            {
                t_result.Text += temp_log;
                t_result.SelectionStart = t_result.Text.Length;
                t_result.ScrollToCaret();
                temp_log = "";
            }
        }

        /// <summary>
        /// 用图片显示程序的状态
        /// </summary>
        private void checkstatus()
        {
            icon_work.Image = imageList.Images[imageindex];
        }

        #endregion

        #region bg_getdata 事件

        private void bg_getdata_DoWork(object sender, DoWorkEventArgs e)
        {
            SetThreeState(false);
            ExtractData();
        }
        private void bg_getdata_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (strbuilder.Length > 0)
                addtext();
            try
            {
                //if(taskid>0)
                //    new CollectorNetLib.Collection.CollectionLog().TaskSuccess(taskid, txtWSUID.Text, txtWSPWD.Text);
            }
            catch (Exception ex)
            {
                addtext(string.Format("执行webservice:TaskSuccess异常" + ex.Message), "TM-PHP(" + txtcallcenter.Text + "呼叫中心）返回执行命令webservice:TaskSuccess异常");
            }
            taskid = 0;
            SetThreeState(true);
            Bgfilestar();
        }

        #endregion

        #region 关闭事件

        private void ICON_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
            }
        }

        private void F_Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing && userclose)
            {
                e.Cancel = true;
                this.Hide();

                ICON.BalloonTipTitle = "SINOBASE温情提示";
                ICON.BalloonTipText = "程序还在继续运行...\r\t单击托盘图标还原窗体";
                ICON.ShowBalloonTip(2000);
            }

        }
        private void ExitItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void OpenMainItem_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }
        #endregion

        #region 配置文件操作
        private void LoadApp()
        {
            try
            {
                string server = ConfigurationManager.AppSettings["conn"].ToString();
                string[] arr = server.Split(';');
                txtServerPath.Text = arr[0].Substring(arr[0].IndexOf("=") + 1);
                txtUserName.Text = GetAppitem(arr[1].Substring(arr[1].IndexOf("=") + 1), false);
                txtPwd.Text = GetAppitem(arr[2].Substring(arr[2].IndexOf("=") + 1), false);
                txtServerNmae.Text = GetAppitem(arr[3].Substring(arr[3].IndexOf("=") + 1), false);


                txtworkdir.Text = System.Configuration.ConfigurationManager.AppSettings["workdir"].ToString();
                txtcallcenter.Text = GetAppitem("callcenter", true);
                txtftppassword.Text = GetAppitem("ftppassword", true);
                txtftpserver.Text = GetAppitem("ftpserver", true);
                txtftpuser.Text = GetAppitem("ftpuser", true);
                txtlogaddr.Text = System.Configuration.ConfigurationManager.AppSettings["logaddr"].ToString();
                txtworkhour.Text = System.Configuration.ConfigurationManager.AppSettings["workhour"].ToString();
                txtworkmin.Text = System.Configuration.ConfigurationManager.AppSettings["workmin"].ToString();
                txtEmail.Text = System.Configuration.ConfigurationManager.AppSettings["emails"].ToString();
                txtWSUID.Text = GetAppitem("WSUID", true);
                txtWSPWD.Text = GetAppitem("WSPWD", true);
                strConnect = "server=" + txtServerPath.Text + ";user id=" + txtUserName.Text + ";password=" + txtPwd.Text + ";database=" +
                txtServerNmae.Text + ";pooling=false;charset=utf8";
                SetAutoRun.DeteleAndSetAutoRun("CollectorNet", System.Windows.Forms.Application.ExecutablePath);

            }
            catch (Exception ex)
            {
                addtext(string.Format("获取配置文件异常：", ex.Message), "TM-PHP(" + txtcallcenter.Text + "呼叫中心）加载配置文件异常");
            }

        }
        /// <summary>
        /// 解密配置文件字符串 isAppSeting 判断是否来自配置文件
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private string GetAppitem(string value, bool isAppSeting)
        {
            if (isAppSeting)
            {
                return DESEncrypt.DesDecrypt(System.Configuration.ConfigurationManager.AppSettings[value]);
            }
            else
            {
                return DESEncrypt.DesDecrypt(value);
            }
        }
        ///   <summary>   
        ///向.config文件的appKey结写入信息AppValue   保存设置   
        ///   </summary>   
        ///   <param   name="AppKey">节点名</param>   
        ///   <param   name="AppValue">值</param>   
        private void SetValue(string AppKey, string AppValue)
        {
            XmlDocument xDoc = new XmlDocument();
            XmlNode xNode;
            XmlElement xElem1;
            XmlElement xElem2;
            try
            {
                xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
                xNode = xDoc.SelectSingleNode("//appSettings");
                xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
                if (xElem1 != null) xElem1.SetAttribute("value", AppValue);
                else
                {
                    xElem2 = xDoc.CreateElement("add");
                    xElem2.SetAttribute("key", AppKey);
                    xElem2.SetAttribute("value", AppValue);
                    xNode.AppendChild(xElem2);
                }
                xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="AppValue"></param>
        /// <returns></returns>
        private string SetDesEncrypt(string AppValue)
        {
            return DESEncrypt.DesEncrypt(AppValue);
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string conn = "server=" + txtServerPath.Text + ";user id=" + SetDesEncrypt(txtUserName.Text) + "; password=" +
                      SetDesEncrypt(txtPwd.Text) + "; database=" + SetDesEncrypt(txtServerNmae.Text) + "; pooling=false;charset=utf8";
                SetValue("conn", conn);
                SetValue("workdir", txtworkdir.Text);
                SetValue("callcenter", SetDesEncrypt(txtcallcenter.Text));
                SetValue("logaddr", txtlogaddr.Text);
                SetValue("ftpserver", SetDesEncrypt(txtftpserver.Text));
                SetValue("ftpuser", SetDesEncrypt(txtftpuser.Text));
                SetValue("ftppassword", SetDesEncrypt(txtftppassword.Text));
                SetValue("workhour", txtworkhour.Text);
                SetValue("workmin", txtworkmin.Text);
                #region  邮件处理
                StringBuilder emails = new StringBuilder();
                string[] arr = txtEmail.Text.Split(',');
                for (int i = 0; i < arr.Length; i++)
                {
                    if (i == arr.Length - 1)
                        emails.Append(arr[i]);
                    else
                        emails.Append(arr[i] + ",");
                }
                SetValue("emails", emails.ToString());
                #endregion
                SetValue("WSUID", SetDesEncrypt(txtWSUID.Text));
                SetValue("WSPWD", SetDesEncrypt(txtWSPWD.Text));
                strConnect = "server=" + txtServerPath.Text + ";user id=" + txtUserName.Text + ";password=" + txtPwd.Text + ";database=" +
                txtServerNmae.Text + ";pooling=false;charset=utf8";
                MessageBox.Show("保存成功,并将配置文件备份在" + CopyApp() + "。");
            }
            catch (Exception ex)
            {
                addtext(string.Format("保存配置文件失败：", ex.Message), "TM-PHP(" + txtcallcenter.Text + "呼叫中心）保存配置文件异常");
            }

        }
        /// <summary>
        /// 备份配置文件
        /// </summary>
        /// <returns></returns>
        private string CopyApp()
        {
            string path = System.Windows.Forms.Application.ExecutablePath + ".config";
            string newpath = path.Substring(0, path.LastIndexOf(@"\"));
            newpath = newpath.Substring(0, newpath.LastIndexOf(@"\") + 1);
            System.IO.File.Copy(path, newpath + "php.configbak", true);
            return newpath + "php.configbak";
        }
        /// <summary>
        /// 还原配置文件
        /// </summary>
        /// <returns></returns>
        private void RevertApp()
        {
            try
            {
                string path = System.Windows.Forms.Application.ExecutablePath;
                path = path.Substring(0, path.LastIndexOf(@"\"));
                path = path.Substring(0, path.LastIndexOf(@"\") + 1) + "php.configbak";
                if (!File.Exists(path))
                {
                    MessageBox.Show("备份文件（" + path + "）不存在");
                    return;
                }
                string newpath = System.Windows.Forms.Application.ExecutablePath + ".config";
                System.IO.File.Copy(path, newpath, true);
                MessageBox.Show("还原成功");
            }
            catch (Exception ex)
            {
                addtext(string.Format("还原配置文件失败：", ex.Message), "TM-B2B(" + txtcallcenter.Text + "呼叫中心）还原配置文件异常");
            }
        }
        private void btnRevert_Click(object sender, EventArgs e)
        {
            RevertApp();
            System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);
            userclose = false;
            Close();
        }
        #endregion

        #region 控制台队列执行

        private List<string> taskLisk;

        public List<string> TaskLisk
        {
            get
            {
                if (taskLisk == null || taskLisk.Count == 0)
                {
                    taskLisk = new List<string>();
                    if (!bg_getdata.IsBusy)
                    {
                        taskLisk = GetOrder();
                    }
                }
                return taskLisk;
            }
            set { taskLisk = value; }
        }

        private void t_order_Tick(object sender, EventArgs e)
        {
            if (!bg_getdata.IsBusy && TaskLisk.Count > 0)
            {
                t_getdata.Stop();
                //执行任务
                doTask(TaskLisk[0]);
            }

        }

        public void doTask(string task)
        {
            string[] array = task.Split('|');
            TaskLisk.Remove(task);
            if (array.Length != 10)
            {
                addtext("命令不符合规范", "控制台操作命令错误提示");
                return;
            }
            startdate = Convert.ToDateTime(array[6]);
            enddate = Convert.ToDateTime(array[7]);
            string taskType = array[5];
            taskid = int.Parse(array[0]);
            if (!string.IsNullOrEmpty(array[4]))
            {
                Identifiers = array[4];
            }
            switch (taskType)
            {
                case ("collect"):
                    {
                        collect();
                        break;
                    }
                case ("sotpcollect"):
                    {
                        sotpcollect();
                        break;
                    }
                case ("recollectbydate"):
                    {
                        recollectbydate();
                        break;
                    }
                default:
                    break;
            }

        }
        /// <summary>
        /// 重新执行
        /// </summary>
        /// <param name="task"></param>
        private void recollectbydate()
        {
            bg_getdata.RunWorkerAsync();
        }

        /// <summary>
        /// 暂停按时执行
        /// </summary>
        /// <param name="task"></param>
        private void sotpcollect()
        {
            t_getdata.Stop();
            addtext("暂停按时执行");
        }
        /// <summary>
        /// 按时执行
        /// </summary>
        /// <param name="task"></param>
        private void collect()
        {
            t_getdata.Start();
            addtext("开启按时执行");
        }
        /// <summary>
        /// 通过webService获取任务列表
        /// </summary>
        /// <returns></returns>
        private List<string> GetOrder()
        {
            //try
            //{
            //    List<string> orderlist = new CollectorNetLib.Collection.CollectionLog().GetUnTaskList(APPLICATION, txtcallcenter.Text, SERVICETYPE, txtWSUID.Text, txtWSPWD.Text).ToList();
            //    if (orderlist != null)
            //        return orderlist;
            //    else 
            //        return new List<string>();
            //}
            //catch (Exception ex)
            //{
            //    addtext("获取WebService控制台命令异常:" + ex);
            //}
            return new List<string>();
        }

        #endregion

        #region 文件上传
        private void tb_UpFile_Click(object sender, EventArgs e)
        {
            Bgfilestar();
        }
        private void bg_Upfile_DoWork(object sender, DoWorkEventArgs e)
        {
            SetThreeState(false);
            DataTable dt_project = getProjectByAll();
            if (dt_project.Rows.Count > 0)
            {
                addtext(string.Format("开始上传{1}至{2}这段时间内结案的项目数据。", dt_project.Rows.Count, startdate.ToString("yyyy-MM-dd"), enddate.ToString("yyyy-MM-dd")));
                UpFileForeachProject(dt_project);
            }
            lastdate = DateTime.Today;
            addtext("上传数据结束\r\n");
        }
        private void UpFileForeachProject(DataTable dt_project)
        {
            var myftp = new FtpHelper(txtftpserver.Text, txtftpuser.Text, txtftppassword.Text);
            while (dt_project.Rows.Count > 0)
            {
                DataRow myrow = dt_project.Rows[0];
                string file_back, file_summary, targeturl;
                file_back = string.Format("{0}-{1}-{2}.txt", myrow["pro_id"], myrow["pro_num"], startdate.ToString("yyyyMMdd"));
                file_summary = string.Format("{0}-{1}-{2}-summary.txt", myrow["pro_id"], myrow["pro_num"], startdate.ToString("yyyyMMdd"));
                targeturl = string.Format("{3}/{0}/{2}/{1}/", txtcallcenter.Text, myrow["pro_id"].ToString(), APPLICATION, SERVICETYPE);
                try
                {
                    if (!File.Exists(txtworkdir.Text + file_back))
                    {
                        dt_project.Rows[0].Delete();
                        dt_project.AcceptChanges();
                        continue;
                    }
                    myftp.Upload("Detail/" + targeturl, txtworkdir.Text + file_back);
                    File.Delete(txtworkdir.Text + file_back);
                    myftp.Upload("Summary/" + targeturl, txtworkdir.Text + file_summary);
                    File.Delete(txtworkdir.Text + file_summary);
                    addtext(string.Format("项目:{1}\t上传完成。上传项目详细数据：{1},{2}\t至{3}", myrow["pro_num"], file_back, file_summary, targeturl));
                    dt_project.Rows[0].Delete();
                    dt_project.AcceptChanges();
                }
                catch (Exception ex)
                {
                    addtext("\t上传项目详细数据出错：" + ex.Message);
                }
            }
        }
        private void bg_Upfile_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            SetThreeState(true);
        }
        private void Bgfilestar()
        {
            if (!bg_getdata.IsBusy && !bg_Upfile.IsBusy)
            {
                bg_Upfile.RunWorkerAsync();
            }
        }
        #endregion
    }
}
